﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using FitnessMVC.Data;

namespace FitnessMVCWeb.Helpers
{
    public static class PictureSaver
    {
        private static readonly string userPicRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
            @"assets\private\userpics");
        private static readonly int UserPicMaxSize = (int)(Math.Pow(1024, 2) * 15); // 15Mb limit on pictures...

        public static bool SaveFile(HttpPostedFileBase hpf, out string fileName)
        {
            fileName = "";
            if (hpf.ContentLength > UserPicMaxSize)
                return false;
            try
            {
                string fileExt = Path.GetExtension(hpf.FileName).ToLower();
                if (fileExt != ".jpg" && fileExt != ".jpeg" && fileExt != ".gif"
                    && fileExt != ".png")
                    return false;

                string fullFileName = GetUniqueFileName(userPicRoot, fileExt);
                hpf.SaveAs(Path.Combine(userPicRoot, fullFileName));
                fileName = Path.GetFileName(fullFileName);
            }
            catch
            {
                return false;
            }

            return true;
        }

        private static string GetUniqueFileName(string userPicRoot,string fileExt)
        {
            string fullPath = "";
            bool isUnique = false;
            while (!isUnique)
            {
                var name = Guid.NewGuid().ToString().Substring(0, 13); // Some dirty use of a Guid.
                fullPath = Path.Combine(userPicRoot, name + fileExt);
                if (!File.Exists(fullPath))
                    isUnique = true;                             
            }

            return fullPath;
        }

        public static FileResult GetFileResult(FitnessMVC.Data.UserPicture pic)
        {
            return new FileContentResult(GetUserPicContents(pic), GetContentType(pic));
        }

        private static string GetContentType(UserPicture pic)
        {
            var ext = Path.GetExtension(pic.PicturePath);
            ext = ext.ToLower();
            if (ext == ".jpg" || ext == ".jpeg")
                return "image/jpeg";
            else if (ext == ".gif")
                return "image/gif";
            else if (ext == ".png")
                return "image/png";

            return "image/*";
        }

        private static byte[] GetUserPicContents(UserPicture pic)
        {
            return File.ReadAllBytes(Path.Combine(userPicRoot, pic.PicturePath));
        }
    }
}
